﻿using System;
using System.Data.Objects;
using System.Linq;
using AutoPoco.Engine;

namespace DataGeneration
{
    public class RandomSqlRowDataSource<T> : DatasourceBase<T> where T : class
    {
        private readonly ObjectSet<T> _set;
        private readonly Func<T, bool> _where;

        public RandomSqlRowDataSource(ObjectSet<T> set) : this(set, null){}

        public RandomSqlRowDataSource(ObjectSet<T> set, Func<T, bool> where)
        {
            _set = set;
            _where = where;
        }

        public override T Next(IGenerationContext context)
        {
            if (_where != null)
                return _set.AsParallel().Where(_where).Random();
            return _set.Random();
        }
    }

    public class RandomSqlRowIdSource<T, TEntity> : DatasourceBase<T> where TEntity : class
    {
        private readonly ObjectSet<TEntity> _set;
        private readonly Func<TEntity, T> _getId;
        private readonly Func<TEntity, bool> _where;

        public RandomSqlRowIdSource(ObjectSet<TEntity> set, Func<TEntity, T> getId, Func<TEntity, bool> where)
        {
            _set = set;
            _getId = getId;
            _where = where;
        }

        public RandomSqlRowIdSource(ObjectSet<TEntity> set, Func<TEntity, T> getId) :this(set, getId, null)
        {
        }

        public override T Next(IGenerationContext context)
        {
            
            if (_where != null)
                return _getId(_set.AsParallel().Where(_where).Random());
            return _getId(_set.Random());
        }
    }
}